package com.atguigu.day12;

import com.atguigu.bean.ResultBean;
import com.atguigu.bean.WaterSensor1;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.types.KeyValueDataType;
import org.apache.flink.table.types.logical.MapType;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.e;

public class Flink05_SQL_TableAPI_Query {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.获取表的环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //TODO 3.想将Table注册为带表名的表

        //从端口读取数据
        SingleOutputStreamOperator<WaterSensor1> streamSource = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor1>() {
                    @Override
                    public WaterSensor1 map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor1(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        //将流转为表
        Table table = tableEnv.fromDataStream(streamSource);
        //使用TableAPI查询
       /* Table result = table.groupBy($("id"))
                .select($("id"), $("vc").sum().as("sumVc"));

        //将表转为撤回流
        DataStream<Row> rowDataStream = tableEnv.toChangelogStream(result);

        rowDataStream.print();

        env.execute();*/

        //结合TableAPI与sql一起使用
        //SQL查询
        Table subTable = tableEnv.sqlQuery("select * from " + table);

        //TableAPI查询
        Table result = subTable.where($("id").isEqual("s1"))
                .select($("id"), $("sensorTs"));

        //SQL
//        result.execute().print();

        DataStream<ResultBean> resultBeanDataStream = tableEnv.toDataStream(result, ResultBean.class);

        //DataStreamAPI
        resultBeanDataStream.map(new MapFunction<ResultBean, String>() {
            @Override
            public String map(ResultBean value) throws Exception {
                return value+"这是最终版本";
            }
        }).print();




        env.execute();
    }
}
